<template>
  <div class="question-management">
    <n-card title="问答管理" :bordered="false" size="small" class="h-full shadow-sm rounded-8px">
      <!-- 搜索区域 -->
      <n-space class="pb-12px" justify="space-between">
        <n-space>
          <n-input
            v-model:value="searchParams.keyword"
            placeholder="搜索用户手机号"
            clearable
            class="w-200px"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <icon-park-outline-search class="text-16px" />
            </template>
          </n-input>
          <n-select
            v-model:value="searchParams.expert_id"
            placeholder="选择专家"
            clearable
            class="w-150px"
            :options="expertOptions"
          />
          <n-select
            v-model:value="searchParams.status"
            placeholder="问答状态"
            clearable
            class="w-120px"
            :options="statusOptions"
          />
          <n-select
            v-model:value="searchParams.rating"
            placeholder="用户评分"
            clearable
            class="w-120px"
            :options="ratingOptions"
          />
          <n-date-picker
            v-model:value="searchParams.dateRange"
            type="daterange"
            placeholder="选择时间范围"
            clearable
            class="w-240px"
          />
          <n-button type="primary" @click="handleSearch">搜索</n-button>
          <n-button @click="handleReset">重置</n-button>
        </n-space>
        <n-space>
          <n-button @click="handleExport">
            <template #icon>
              <icon-park-outline-download />
            </template>
            导出数据
          </n-button>
        </n-space>
      </n-space>

      <!-- 统计卡片 -->
      <n-grid :cols="4" :x-gap="16" class="mb-16px">
        <n-grid-item>
          <n-statistic label="总问答数" :value="statistics.total" />
        </n-grid-item>
        <n-grid-item>
          <n-statistic label="已回答" :value="statistics.answered" />
        </n-grid-item>
        <n-grid-item>
          <n-statistic label="满意评分" :value="statistics.satisfied" />
        </n-grid-item>
        <n-grid-item>
          <n-statistic label="满意率" :value="satisfactionRate" suffix="%" />
        </n-grid-item>
      </n-grid>

      <!-- 表格 -->
      <n-data-table
        :columns="columns"
        :data="tableData"
        :loading="loading"
        :pagination="pagination"
        :row-key="(row) => row.id"
        remote
        @update:page="handlePageChange"
        @update:page-size="handlePageSizeChange"
      />
    </n-card>

    <!-- 问答详情弹窗 -->
    <n-modal v-model:show="detailVisible" preset="dialog" title="问答详情" style="width: 90%; max-width: 1200px;">
      <div v-if="currentQuestion" class="question-detail-container">
        <!-- 三列布局 -->
        <n-grid :cols="3" :x-gap="24" class="h-full">
          <!-- 第一列：基本信息 -->
          <n-grid-item>
            <div class="detail-column">
              <h4 class="column-title">基本信息</h4>
              <n-descriptions :column="1" bordered size="small">
                <n-descriptions-item label="问题ID">
                  {{ currentQuestion.id }}
                </n-descriptions-item>
                <n-descriptions-item label="用户手机号">
                  {{ currentQuestion.user?.phone }}
                </n-descriptions-item>
                <n-descriptions-item label="专家">
                  {{ currentQuestion.expert?.nickname }}
                </n-descriptions-item>
                <n-descriptions-item label="所属领域">
                  {{ currentQuestion.expert?.domain?.name }}
                </n-descriptions-item>
                <n-descriptions-item label="提问时间">
                  {{ formatTime(currentQuestion.created_at) }}
                </n-descriptions-item>
                <n-descriptions-item label="回答时间" v-if="currentQuestion.updated_at && currentQuestion.status === 'answered'">
                  {{ formatTime(currentQuestion.updated_at) }}
                </n-descriptions-item>
                <n-descriptions-item label="状态">
                  <n-tag :type="getStatusType(currentQuestion.status)">
                    {{ getStatusText(currentQuestion.status) }}
                  </n-tag>
                </n-descriptions-item>
                <n-descriptions-item label="用户评分" v-if="currentQuestion.rating">
                  <n-tag :type="getRatingType(currentQuestion.rating)">
                    {{ getRatingText(currentQuestion.rating) }}
                  </n-tag>
                </n-descriptions-item>
                <n-descriptions-item label="Request ID" v-if="currentQuestion.ai_request_id">
                  <n-code :code="currentQuestion.ai_request_id" />
                </n-descriptions-item>
                <n-descriptions-item label="额度ID">
                  {{ currentQuestion.user_quota_id }}
                </n-descriptions-item>
              </n-descriptions>

              <!-- 错误信息 -->
              <div v-if="currentQuestion.error_message" class="mt-16px">
                <h5 class="text-14px font-semibold mb-8px text-red-500">错误信息</h5>
                <n-card size="small" class="error-card">
                  <p class="text-red-500 text-12px">{{ currentQuestion.error_message }}</p>
                </n-card>
              </div>
            </div>
          </n-grid-item>

          <!-- 第二列：前置条件 -->
          <n-grid-item>
            <div class="detail-column">
              <h4 class="column-title">前置条件</h4>
              <div v-if="currentQuestion.preconditions && Object.keys(currentQuestion.preconditions).length > 0">
                <n-card size="small" class="preconditions-card">
                  <div class="space-y-12px">
                    <div v-for="(value, key) in currentQuestion.preconditions" :key="key" class="precondition-item">
                      <div class="precondition-label">{{ formatPreconditionLabel(key) }}</div>
                      <div class="precondition-value">
                        <n-tag v-if="Array.isArray(value)" type="info" size="small" class="mr-4px mb-4px" v-for="item in value" :key="item">
                          {{ item }}
                        </n-tag>
                        <span v-else class="text-14px">{{ value }}</span>
                      </div>
                    </div>
                  </div>
                </n-card>
              </div>
              <div v-else class="empty-state">
                <n-empty description="无前置条件" size="small" />
              </div>
            </div>
          </n-grid-item>

          <!-- 第三列：问题和回答 -->
          <n-grid-item>
            <div class="detail-column">
              <h4 class="column-title">问题与回答</h4>

              <!-- 用户问题 -->
              <div class="question-section">
                <h5 class="section-title">用户问题</h5>
                <n-card size="small" class="question-card">
                  <p class="question-content">{{ currentQuestion.question }}</p>
                </n-card>
              </div>

              <!-- 专家回答 -->
              <div v-if="currentQuestion.answer" class="answer-section">
                <h5 class="section-title">专家回答</h5>
                <n-card size="small" class="answer-card">
                  <div class="answer-content" v-html="formatAnswer(currentQuestion.answer)"></div>
                </n-card>
              </div>

              <!-- 无回答状态 -->
              <div v-else-if="currentQuestion.status === 'pending'" class="no-answer-state">
                <n-empty description="等待专家回答" size="small">
                  <template #icon>
                    <icon-park-outline-time class="text-24px text-orange-500" />
                  </template>
                </n-empty>
              </div>

              <div v-else-if="currentQuestion.status === 'failed'" class="no-answer-state">
                <n-empty description="回答失败" size="small">
                  <template #icon>
                    <icon-park-outline-close-one class="text-24px text-red-500" />
                  </template>
                </n-empty>
              </div>
            </div>
          </n-grid-item>
        </n-grid>
      </div>
      <template #action>
        <n-space>
          <n-button @click="detailVisible = false">关闭</n-button>
          <n-button type="primary" @click="handleViewPreview" v-if="currentQuestion">
            预览页面
          </n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, h } from 'vue'
import type { DataTableColumns } from 'naive-ui'
import { NButton, NTag, NSpace, useMessage } from 'naive-ui'
import { questionApi, expertApi, serviceIntegrationApi } from '@/service/api/bizhi'
import { filterApiParams } from '@/utils/api'
import { formatTime } from '@/utils/time'
import { useRoute } from 'vue-router'

const message = useMessage()
const route = useRoute()

// 响应式数据
const loading = ref(false)
const detailVisible = ref(false)
const tableData = ref([])
const currentQuestion = ref<any>(null)
const expertOptions = ref([])
const previewBaseUrl = ref('')

// 搜索参数
const searchParams = reactive({
  keyword: '',
  expert_id: null,
  status: null,
  rating: null,
  dateRange: null,
  page: 1,
  limit: 20
})

// 统计数据
const statistics = reactive({
  total: 0,
  answered: 0,
  satisfied: 0
})

// 状态选项
const statusOptions = [
  { label: '处理中', value: 'pending' },
  { label: '已回答', value: 'answered' },
  { label: '失败', value: 'failed' }
]

// 评分选项
const ratingOptions = [
  { label: '不满意', value: 'unsatisfied' },
  { label: '一般', value: 'normal' },
  { label: '满意', value: 'satisfied' }
]

// 分页配置
const pagination = reactive({
  page: 1,
  pageSize: 20,
  itemCount: 0,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100]
})

// 满意率计算
const satisfactionRate = computed(() => {
  const total = statistics.answered
  return total > 0 ? ((statistics.satisfied / total) * 100).toFixed(1) : '0.0'
})

// 获取状态类型
const getStatusType = (status: string): 'default' | 'error' | 'warning' | 'success' | 'primary' | 'info' => {
  const typeMap: Record<string, 'default' | 'error' | 'warning' | 'success' | 'primary' | 'info'> = {
    pending: 'warning',
    answered: 'success',
    failed: 'error'
  }
  return typeMap[status] || 'default'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    pending: '处理中',
    answered: '已回答',
    failed: '失败'
  }
  return textMap[status] || status
}

// 获取评分类型
const getRatingType = (rating: string): 'default' | 'error' | 'warning' | 'success' | 'primary' | 'info' => {
  const typeMap: Record<string, 'default' | 'error' | 'warning' | 'success' | 'primary' | 'info'> = {
    unsatisfied: 'error',
    normal: 'warning',
    satisfied: 'success'
  }
  return typeMap[rating] || 'default'
}

// 获取评分文本
const getRatingText = (rating: string) => {
  const textMap: Record<string, string> = {
    unsatisfied: '不满意',
    normal: '一般',
    satisfied: '满意'
  }
  return textMap[rating] || rating
}

// 表格列配置
const columns: DataTableColumns = [
  { title: 'ID', key: 'id', width: 80 },
  { title: '用户手机号', key: 'user.phone', width: 120 },
  { title: '专家', key: 'expert.nickname', width: 120 },
  { title: '领域', key: 'expert.domain.name', width: 100 },
  { 
    title: '问题', 
    key: 'question', 
    width: 200,
    ellipsis: { tooltip: true }
  },
  {
    title: '状态',
    key: 'status',
    width: 100,
    render: (row: any) => {
      return h(NTag, {
        type: getStatusType(row.status)
      }, {
        default: () => getStatusText(row.status)
      })
    }
  },
  {
    title: '用户评分',
    key: 'rating',
    width: 100,
    render: (row: any) => {
      if (!row.rating) return '-'
      return h(NTag, {
        type: getRatingType(row.rating)
      }, {
        default: () => getRatingText(row.rating)
      })
    }
  },
  {
    title: '提问时间',
    key: 'created_at',
    width: 180,
    render: (row: any) => formatTime(row.created_at)
  },
  {
    title: '操作',
    key: 'actions',
    width: 120,
    render: (row: any) => {
      return h(NButton, {
        size: 'small',
        type: 'primary',
        onClick: () => handleViewDetail(row)
      }, { default: () => '查看详情' })
    }
  }
]

// 获取专家选项
const fetchExpertOptions = async () => {
  try {
    // 管理后台应该显示所有专家，不仅仅是启用的专家
    const response = await expertApi.getExpertList({})
    
    // 检查响应结构
    if (response && (response as any).data && (response as any).data.list) {
      expertOptions.value = (response as any).data.list.map((expert: any) => ({
        label: expert.nickname,
        value: expert.id
      }))
    } else {
      expertOptions.value = []
    }
  } catch (error) {
    console.error('获取专家列表失败:', error)
    message.error('获取专家列表失败')
    expertOptions.value = []
  }
}

// 获取统计数据
const fetchStatistics = async () => {
  try {
    const response = await questionApi.getQuestionStats()
    if ((response as any).code === 200) {
      Object.assign(statistics, (response as any).data)
    } else {
      message.error((response as any).message || '获取统计数据失败')
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
    message.error('获取统计数据失败')
  }
}

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    const params = filterApiParams(searchParams)
    const response = await questionApi.getQuestionList(params)
    
    // 检查响应结构
    if (response && (response as any).data) {
      tableData.value = (response as any).data.list || []
      pagination.itemCount = (response as any).data.pagination?.total || 0
    } else {
      tableData.value = []
      pagination.itemCount = 0
    }
  } catch (error) {
    console.error('获取问答数据失败:', error)
    message.error('获取数据失败')
    tableData.value = []
    pagination.itemCount = 0
  } finally {
    loading.value = false
  }
}

// 查看详情
const handleViewDetail = (row: any) => {
  currentQuestion.value = row
  detailVisible.value = true
}

// 格式化前置条件标签
const formatPreconditionLabel = (key: string | number) => {
  const labelMap: Record<string, string> = {
    child_age: '孩子年龄',
    child_gender: '孩子性别',
    concern_areas: '关注领域',
    age_group: '年龄段',
    consultation_type: '咨询类型',
    health_goal: '健康目标',
    current_issues: '当前问题',
    career_stage: '职业阶段',
    industry: '所在行业',
    relationship_status: '感情状态',
    consultation_focus: '咨询重点',
    legal_area: '法律领域',
    urgency: '紧急程度',
    investment_experience: '投资经验',
    financial_goals: '理财目标',
    education_stage: '教育阶段',
    subject_areas: '学科领域',
    fitness_goal: '健身目标',
    exercise_experience: '运动基础',
    skin_type: '肌肤类型',
    skin_concerns: '肌肤问题'
  }
  return labelMap[String(key)] || String(key)
}

// 格式化回答内容（支持Markdown格式）
const formatAnswer = (answer: string) => {
  if (!answer) return ''

  // 简单的Markdown格式转换
  return answer
    .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>') // 粗体
    .replace(/\*(.*?)\*/g, '<em>$1</em>') // 斜体
    .replace(/\n\n/g, '</p><p>') // 段落
    .replace(/\n/g, '<br>') // 换行
    .replace(/^/, '<p>') // 开始段落
    .replace(/$/, '</p>') // 结束段落
}

// 获取预览页面基础URL
const loadPreviewBaseUrl = async () => {
  try {
    const result = await serviceIntegrationApi.getServiceConfig('system_a') as any
    const config = result.data
    if (config?.api_config?.expertDetailPage?.urlTemplate) {
      // 从专家详情页URL模板中提取基础URL
      const urlTemplate = config.api_config.expertDetailPage.urlTemplate
      try {
        // 将占位符替换为临时值以便解析URL
        const tempUrl = urlTemplate.replace('{expert_id}', '1')
        const url = new URL(tempUrl)
        previewBaseUrl.value = `${url.protocol}//${url.host}`
        console.log('从服务联动配置获取预览基础URL:', previewBaseUrl.value)
      } catch (urlError) {
        console.error('解析URL模板失败:', urlError)
        previewBaseUrl.value = window.location.origin
      }
    } else {
      // 如果没有配置，使用当前域名
      previewBaseUrl.value = window.location.origin
      console.log('使用当前域名作为预览基础URL:', previewBaseUrl.value)
    }
  } catch (error) {
    console.error('获取预览基础URL失败:', error)
    // 如果获取失败，使用当前域名
    previewBaseUrl.value = window.location.origin
  }
}

// 查看预览页面
const handleViewPreview = () => {
  if (currentQuestion.value) {
    // 使用从服务联动配置中获取的基础URL
    const baseUrl = previewBaseUrl.value || window.location.origin
    const url = `${baseUrl}/preview/question/${currentQuestion.value.id}`
    window.open(url, '_blank')
  }
}

// 导出数据
const handleExport = async () => {
  try {
    // TODO: 调用导出API
    message.success('导出成功')
  } catch (error) {
    message.error('导出失败')
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchData()
}

// 重置
const handleReset = () => {
  Object.assign(searchParams, {
    keyword: '',
    expert_id: null,
    status: null,
    rating: null,
    dateRange: null,
    page: 1,
    limit: 20
  })
  fetchData()
}

// 分页变化
const handlePageChange = (page: number) => {
  pagination.page = page
  searchParams.page = page
  fetchData()
}

const handlePageSizeChange = (pageSize: number) => {
  pagination.pageSize = pageSize
  pagination.page = 1
  searchParams.limit = pageSize
  searchParams.page = 1
  fetchData()
}

onMounted(() => {
  // 处理URL查询参数
  const { user_phone } = route.query
  if (user_phone) {
    searchParams.keyword = user_phone as string
    message.info(`正在显示用户 ${user_phone} 的问答记录`)
  }

  fetchExpertOptions()
  fetchStatistics()
  fetchData()
  loadPreviewBaseUrl()
})
</script>

<style scoped>
.question-management {
  height: 100%;
}

/* 问答详情弹窗样式 */
.question-detail-container {
  min-height: 600px;
  max-height: 80vh;
  overflow: hidden;
}

.detail-column {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.column-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin: 0 0 16px 0;
  padding-bottom: 8px;
  border-bottom: 2px solid #f0f0f0;
}

.section-title {
  font-size: 14px;
  font-weight: 600;
  color: #666;
  margin: 0 0 8px 0;
}

/* 前置条件样式 */
.preconditions-card {
  max-height: 400px;
  overflow-y: auto;
}

.precondition-item {
  padding: 8px 0;
  border-bottom: 1px solid #f5f5f5;
}

.precondition-item:last-child {
  border-bottom: none;
}

.precondition-label {
  font-size: 12px;
  color: #999;
  margin-bottom: 4px;
}

.precondition-value {
  font-size: 14px;
  color: #333;
}

/* 问题和回答样式 */
.question-section {
  margin-bottom: 20px;
}

.answer-section {
  margin-bottom: 20px;
}

.question-card {
  border-left: 3px solid #2080f0;
}

.answer-card {
  border-left: 3px solid #18a058;
}

.question-content {
  font-size: 14px;
  line-height: 1.6;
  color: #333;
  margin: 0;
  white-space: pre-wrap;
  word-break: break-word;
}

.answer-content {
  font-size: 14px;
  line-height: 1.6;
  color: #333;
  word-break: break-word;
}

.answer-content :deep(p) {
  margin: 0 0 12px 0;
}

.answer-content :deep(p:last-child) {
  margin-bottom: 0;
}

.answer-content :deep(strong) {
  font-weight: 600;
  color: #2080f0;
}

.answer-content :deep(em) {
  font-style: italic;
  color: #666;
}

/* 空状态样式 */
.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
}

.no-answer-state {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 150px;
}

/* 错误信息样式 */
.error-card {
  border-left: 3px solid #d03050;
  background-color: #fef2f2;
}

/* 响应式调整 */
@media (max-width: 1024px) {
  .question-detail-container {
    min-height: 500px;
  }

  .column-title {
    font-size: 14px;
  }

  .section-title {
    font-size: 13px;
  }
}
</style>
